﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FaWorks.WebSite.Controllers.Model
{
    public class ModelsController : Controller
    {
        #region GetModel
        // ~/Model/User
        public ActionResult GetModel(string typeName)
        {
            Type type = this.GetRequestType(typeName);

            bool flagFirst = true;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("App.{0} = DS.Model.extend(", type.Name);
            sb.Append("{");
            foreach (PropertyInfo pi in type.GetProperties()) {
                if (pi.Name == "id") continue;
                
                if (!pi.PropertyType.Name.StartsWith("List"))
                {
                    if (!flagFirst)
                    {
                        sb.Append(",");
                    }
                    sb.AppendFormat("{0}: DS.attr({1})", pi.Name, ConvertToEmberType(pi.PropertyType.Name));
                    flagFirst = false;
                }
                else {
                    //sb.AppendFormat("{0}: DS.hasMany('App.{1}')", pi.Name, pi.PropertyType.GenericTypeArguments[0].Name);
                }
            }
            sb.Append("});");

            return JavaScript(sb.ToString());
        }

        private string ConvertToEmberType(string pName) {
            string type;

            switch (pName)
            {
                case "DateTime":
                    type = "date";
                    break;
                case "Int16":
                case "Int32":
                case "Int64":
                    type = "number";
                    break;
                case "Boolean":
                    type = "boolean";
                    break;
                default:
                    type = "string";
                    break;
            }

            return string.Format("'{0}'", type);
        }
        #endregion

        private Type GetRequestType(string typeName)
        {
            var index = typeName.LastIndexOf("-");
            var ns = typeName.Substring(0, index > -1 ? index : 0);
            typeName = typeName.Substring(index + 1);
            ns = (ns.Length > 0 ? "." : "") + ns.Replace("-", ".");
            Assembly assembly = this.GetType().Assembly;
            Type type = (from t in assembly.GetTypes()
                         where t.Namespace != null && t.Namespace.EndsWith(".Models" + ns) && t.Name == typeName
                         select t).FirstOrDefault<Type>();
            if (type == null)
            {
                throw new FileNotFoundException();
            }

            return type;
        }
    }
}